package com.shiro.test.javase;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class MyRealm2 extends AuthorizingRealm {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //每次进行权限验证时调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("doGetAuthorizationInfo");
        String sql = "select ROLE_NAME from SHIRO_USER_ROLE where USER_NAME = ?";
        String username =(String)principals.getPrimaryPrincipal();
        List<String> roles = jdbcTemplate.queryForList(sql,String.class,username);
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        info.addRoles(roles);
        return info;
    }

    //每次登录的时候调用
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("doGetAuthenticationInfo");
        String sql = "select PASSWORD from SHIRO_USER where USER_NAME = ?";
        String username = (String) authenticationToken.getPrincipal();
        String password = jdbcTemplate.queryForObject(sql,String.class,username);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,password,null,getName());
        return info;
    }
}
